package cn.gson.crm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class UploadController {
    String uri = "E:/upload";

    @GetMapping("upload/**")
    public void upload(HttpServletRequest request,
                       HttpServletResponse response) {
        String servletPath = request.getServletPath();
        String path = uri + "/" + servletPath.replaceFirst("/upload/","");
        System.out.println(path);
        //判断
        File file = new File(path);
        if(!file.exists()) {
            //抛出异常
            try {
                response.sendError(404, "文件路径不存在");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            //使用字节流把图片从本地盘中读取到内存
            InputStream is = new FileInputStream(file);
            //servlet中的流将图片传回客户端显示
            ServletOutputStream s = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            //循环读取
            while((len = is.read(b)) != -1) {
                s.write(b, 0, len);
            }
            s.close();
            is.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
